<?php
namespace App\Http\Controllers\Api\Customer;

use Carbon\Carbon;

use App\Service\WdhService;

use App\Models\Card\CardCouponCode; //活动码池子表

use App\Models\Goods\GoodsSaleEdit; //待发布商品表

use App\Models\Card\CardCouponMall; //卡券指定使用门店表

use App\Models\Card\CardCouponCodeGive; //卡券券码赠送记录表

use App\Models\Card\CardCouponReleaseMap; //卡券第三方同步关联表

use App\Models\Wx\WechatCustomerCouponMap; //领取微信卡劵信息

use App\Models\Card\CardCoupon; //卡券表

use App\Models\Bill\Bill; //订单主表

use App\Models\Mall\MallMaster; //门店主表

use App\Models\Mall\MallUser; //门店用户表

use App\Models\Customer\Customer; //会员表

use App\Models\Customer\CustRank; //会员等级表

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Redis as Redis;

class CustomerCardController extends Controller
{

    /**
     * 卡券列表初始化接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function init( Request $request ){

        $session_id = $request->input('session_id',session_id());
        $platform = $request->input('platform',6);

        if ( empty( $session_id ) ) {
            return response()->json(['code' => 100000, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);

        //已领取未使用且未过期券码
        $no_use_num = CardCouponCode::where([
            ['pcustID', '=', $pcustID],
            ['code_type', '>', 5],
            ['code_status', '=', 1],
            ['code_end_time', '>=', Carbon::now()]
        ])->count();

        //查询已使用的券码
        $use_num = CardCouponCode::where([
            ['pcustID', '=', $pcustID],
            ['code_type', '>', 5],
            ['code_status', '=', 2]
        ])->count();

        //查询已过期券码
        $out_date_num = CardCouponCode::where([
            ['pcustID', '=', $pcustID],
            ['code_type', '>', 5],
            ['code_status', '=', 1],
            ['code_end_time', '<', Carbon::now()]
        ])->count();

        return response()->json([
            'code' => 200 ,
            'message' => 'ok',
            'data' => [
                'no_use_num' => isset( $no_use_num ) ? $no_use_num : 0,
                'use_num'=>isset( $use_num ) ? $use_num : 0,
                'out_date_num'=>isset( $out_date_num ) ? $out_date_num : 0
            ]
        ]);
    }


    /**
     * 卡券列表页获取卡券信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function search( Request $request )
    {

        $session_id = $request->input('session_id',session_id());
        $platform = $request->input('platform',6);
        $limit = $request->input('limit');
        $type = $request->input('type');
        $page = $request->input('page');

        if ( empty( $session_id ) ) {
            return response()->json(['code' => 10000, 'message' => '缺少参数：session_id']);
        }
        if ( !in_array( $type ,array(1,2,3) )) {
            return response()->json(['code' => 10001, 'message' => '参数错误']);
        }

        if (!ebsig_is_int($limit)) {
            $limit = 10;
        }

        if (!ebsig_is_int($page)) {
            $page = 1;
        }

        $pcustID = get_customer_id($session_id, $platform);

        $where = [];
        $where[] = ['pcustID', '=', $pcustID];
        $where[] = ['code_type', '>', 5];

        if ( $type == 1 ) {  //已领取未使用且未过期券码
            $where[] = ['code_status', '=', 1];
            $where[] = ['code_end_time', '>=', Carbon::now()];
        } else if ( $type == 2 ) {  //查询已使用的券码
            $where[] =['code_status', '=', 2];
        } else {  //查询已过期券码
            $where[] = ['code_status', '=', 1];
            $where[] = ['code_end_time', '<', Carbon::now()];
        }

        $code_data = CardCouponCode::where($where)->orderBy('get_time', 'DESC')->paginate($limit)->toArray();
        if ( !$code_data ) {
            return response()->json([ 'code' => 100002, 'message' => '没有卡券数据' ]);
        }

        $code_array = [];

        foreach ( $code_data['data'] as $code ) {

            //如果是提货券的时候标题显示商品名称
            $goods_name = $code['activity_name'];
            if ( $code['code_type'] == 8  &&  !empty( $code['postID'] ) ) {
                $goods_sale = GoodsSaleEdit::select( 'goodsName' )->where( ['postID'=>$code['postID']] )->first();
                if ( $goods_sale ) {
                    $goods_name = $goods_sale['goodsName'];
                }
            }

            $privilege_description = '';   //获取通用券使用说明
            $give = 0; //卡券是否可转赠

            $card_data = CardCoupon::select( 'privilege_description','can_give_friend' )->where( ['card_id'=>$code['activity_id']] )->first();

            if ( $card_data ) {

                $privilege_description = $card_data['privilege_description'];
                if ( $card_data['can_give_friend'] == 1 ) {

                    $code_give = CardCouponCodeGive::select('id')->where( ['barcode'=>$code['barcode']] )->get()->toArray();

                    if ( $code_give ) {
                        $give = 1 ;
                    } else {
                        $give = 2 ;
                    }

                } else if ( $card_data['can_give_friend'] == 2  ) {
                    $give = 2  ;
                }
            }

            $code_array[] = [
                'barcode' => $code['barcode'],
                'code_use_type' => $code['code_use_type'],
                'activity_name' => $code['activity_name'],
                'goods_name' => $goods_name,
                'give' => $give, //0,不可转赠，1，朋友赠送， 2 ，可转赠
                'code_amount' => $code['code_amount'],
                'limit_money' => $code['code_limit_amount'],
                'code_discount' => $code['code_discount']/100,
                'sale_price' => $code['sale_price'],
                'market_price' => $code['market_price'],
                'privilege_description' => $privilege_description,//优惠说明
                'code_start_time_show' => date('Y.m.d',strtotime($code['code_start_time'])),//有效开始时间
                'code_end_time_show' => date('Y.m.d',strtotime($code['code_end_time']))//有效结束时间
            ];

        }

        return response()->json([
            'code' => 200 ,
            'message' => 'ok',
            'data' => [
                'page' => $page,
                'limit' => $limit,
                'count' => $code_data['total'],
                'list' => $code_array
            ]
        ]);

    }


    /**
     * 卡券详情页
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function detail( Request $request )
    {

        $barcode = $request->input('code');
        $session_id  = $request->input('session_id',session_id());

        if ( empty( $barcode ) ) {
            return response()->json(['code' => 10000, 'message' => '缺少参数：barcode']);
        }

        $code_data = CardCouponCode::find( $barcode );
        if ( !$code_data ) {
            return response()->json(['code' => 10001, 'message' => '券码信息没有找到']);
        }

        $card_data = CardCoupon::find( $code_data['activity_id'] );
        if ( empty( $card_data ) || $card_data['useFlg'] == 0 ) {
            return response()->json(['code' => 10002, 'message' => '卡券信息没有找到']);
        }

        $code_status = 0 ;
        if ( $code_data['code_status'] == 1 && $code_data['code_end_time'] >= Carbon::now() ) { //已领取,未使用,未过期
            $code_status = 1 ;
        } else if ( ( $code_data['code_status'] == 1 && $code_data['code_end_time'] < Carbon::now() )|| $code_data['code_status'] == 3 ) { //已过期
            $code_status = 3 ;
        } else if ( $code_data['code_status'] == 2 ) { //已使用
            $code_status = 2 ;
        }

        //同步微信卡包
        $wx_card = [
            'is_to_wechat' => 0,   // 0 不同步卡包  1 同步卡包
            'to_wechat_stat' => 0  // 0 未领取  1 已领取
        ];

        $card_release = CardCouponReleaseMap::select('wechat_card_id','release_status')->where( ['card_id'=>$code_data['activity_id'] ])->first();

        if ( isset( $card_data['is_to_wechat'] ) && !empty( $card_data['is_to_wechat'] ) && !empty( $card_release['wechat_card_id'] ) && $card_release['release_status'] == 2 ){
            if ( !empty($card_release['wechat_card_id']) && $card_release['release_status'] == 2 ) {

                if ( redisTransformation( Redis::get('WXCARD_API_TICKET') ) ) {
                    $ticket = redisTransformation( Redis::get('WXCARD_API_TICKET') );
                } else {
                    $ticket  = WdhService::getWxTicket();
                }

                //微信小程序粉丝信息
                $wx_applet_info = json_decode(Redis::get('WX_APPLET_USER_' . $session_id), true);
                if (!$wx_applet_info) {
                    return response()->json([ 'code' => 100006 , 'message' => '小程序身份信息不存在' ]);
                }

                $openId = $wx_applet_info['openId'];
                $card_id = $card_release['wechat_card_id'];
                $nonce_str = makeUuid();
                $timestamp = time();
                $card = [$ticket, $timestamp, $card_id, $barcode, $nonce_str,$openId];
                sort( $card, 2 ) ;
                $signature =  sha1( implode( $card ) );

                $wx_card['is_to_wechat'] = 1;
                $wx_card['coupon'] = [
                    'card_id'=> $card_release['wechat_card_id'],
                    'code' => $barcode,
                    'timestamp'=>$timestamp,
                    'nonce_str'=>$nonce_str,
                    'signature'=>$signature,
                ];
            }

            // 卡劵映射表
            $wx_card_map = WechatCustomerCouponMap::select('pcustID')->where( [['barcode','=',$barcode],['stat','=',1]])->first();
            if ( !empty( $wx_card_map ) ) {
                $wx_card['wechat_package'] = $wx_card_map;
                $wx_card['to_wechat_stat'] = 1;
            }
        }

        //订单支付 0.不可支付,1.可以去支付   code_type 券码类型：8.提货券
        $is_to_pay = 0;
        if ( $code_data['code_type']== 8 && !empty( $code_data['bill_no'] ) ) {
            //查询订单支付状态
            $bill_pay = Bill::select('pay_status','pay_type','split_type')->find($code_data['bill_no']);
            if ( $bill_pay && $bill_pay['split_type'] != 2 && $bill_pay['pay_type'] == 2 && $bill_pay['pay_status'] != 1 ) {
                $is_to_pay = 1;
            }
        }

        //是否可转赠
        $give = 0;
        if ( $card_data['can_give_friend'] == 1 ) {

            //查询券码是否转赠过
            $code_give = CardCouponCodeGive::select('id')->where( ['barcode'=>$barcode] )->get()->toArray();
            if ( !$code_give) {
                $give = 1 ;//可转赠
            }

        } else if ( $card_data['can_give_friend'] == 2 ) {
            $give = 1 ;
        }

        $return_array = [
            'uuid' => $card_data['uuid'],
            'card_name' => $code_data['activity_name'],//卡券名称
            'card_type' => $card_data['card_type'],//卡券类型类型 1.代金券 2.折扣券 3.提货券 4.通用券 5.免运费券
            'code_status' => $code_status,//券码状态 1.已领取（未使用） 2.已领取（已使用） 3.已过期
            'code_amount' => $code_data['code_amount'],//券金额
            'code_discount' => $code_data['code_discount']*0.1,//折扣额度
            'code_limit_amount'=> $code_data['code_limit_amount'],//券使用限额
            'barcode' => $barcode,//券码
            'start_time' => date('Y.m.d',strtotime($code_data['code_start_time'])),//开始时间
            'end_time' => date('Y.m.d',strtotime($code_data['code_end_time'])),//结束时间
            'description' => $card_data['description'] ? $card_data['description'] : '',//使用说明
            'bill_no' => $code_data['bill_no'],//订单号
            'is_to_pay' => $is_to_pay,//  0不可支付  1 可以去支付
            'goods_name' => $code_data['goods_name'],//商品名称
            'sale_price' => $code_data['sale_price'],//商品价格
            'market_price' => $code_data['market_price'],//市场价格
            'goods_num' => $code_data['goods_num'],//商品数量
            'total_price' => $code_data['sale_price']*$code_data['goods_num'],//提货总价
            'take_goods' => $code_data['mall_code'].'-'.$code_data['mall_name'],//提货门店
            'mobile' => $code_data['mobile'],//提货手机
            'code_verify_type' => !empty($code_data['code_verify_type']) ? $code_data['code_verify_type'] : 1,//验码方式 :1.手机端验证 2.接口验证
            'wechat_coupon' => $wx_card ,
            'card_id' => $code_data['activity_id'], //卡券id
            'verify_type' => $card_data['verify_type'],// 0.无条件 1.门店号 2.营业员工号 3.全部
            'privilege_description' => $card_data['privilege_description'], //优惠说明
            'give' => $give //卡券是否可转赠：0、不可转赠，1 ，可转赠
        ];

        return response()->json([
            'code' => 200 ,
            'message' => 'ok',
            'data' => $return_array
        ]);
    }


    /**
     * 卡券核销接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function verify( Request $request )
    {

        $code = $request->input('code');//卡券券码
        $sales_code = $request->input('sales_code');//营业员工号
        $mall_code = $request->input('mall_code');//门店编码

        if ( empty( $code ) ) {
            return response()->json(['code' => 10000, 'message' => '缺少参数：code']);
        }

        $code_data = CardCouponCode::select('activity_id','code_status','code_end_time','code_verify_type')->where( ['barcode'=>$code] )->first();
        if ( !$code_data ) {
            return response()->json(['code' => 10001, 'message' => '券码信息没有找到']);
        }
        if ( $code_data['code_status'] == 0 ){
            return response()->json(['code' => 10002, 'message' => '该券码尚未领取,无法核销']);
        }
        if ( $code_data['code_status'] == 2 ){
            return response()->json(['code' => 10003, 'message' => '该券码已使用，无法核销']);
        }
        if ( $code_data['code_status'] == 3 ){
            return response()->json(['code' => 10004, 'message' => '该券码已放弃，无法核销']);
        }
        if ( $code_data['code_end_time'] < Carbon::now() ) {
            return response()->json(['code' => 10005, 'message' => '该券码已过期']);
        }

        //检查活动码是否支持手机端核销
        if ( $code_data['code_verify_type'] != 1 ) {
            return response()->json(['code' => 10006, 'message' => '该券码不支持在手机端核销']);
        }

        //查询卡券信息
        $card_data = CardCoupon::select('useFlg','verify_type','mall_support_type')->where(['card_id'=>$code_data['activity_id'] ])->first();

        if ( empty( $card_data ) || $card_data['useFlg'] == 0 ) {
            return response()->json(['code' => 10007, 'message' => '没有找到卡券信息或被禁用']);
        }

        $mall_id = 0;//门店id
        $mall_name = null;//门店名称

        //核销条件为门店号或全部
        if ( $card_data['verify_type'] == 1 || $card_data['verify_type'] == 3 ) {

            if ( empty( $mall_code ) ) {
                return response()->json(['code' => 10008, 'message' => '缺少参数：mall_code']);
            }

            $mall_master = MallMaster::select('mallID','mallName')->where(['mallCode'=>$mall_code ])->first();

            if ( !$mall_master ) {
                return response()->json(['code' => 10009, 'message' => '门店信息不存在']);
            }

            //门店支持类型
            if ( $card_data['mall_support_type'] != 1 ) {//部分门店

                $card_coupon_mall = CardCouponMall::select('card_id')->where([
                    ['card_id','=',$code_data['activity_id'] ],
                    ['relation_type','=',1 ],
                    ['relation_id','=',$mall_master['mallID'] ],
                ])->get()->toArray();

                if ( !$card_coupon_mall ) {
                    return response()->json(['code' => 10010, 'message' => '该券不适用于当前门店']);
                }
            }

            $mall_id= $mall_master['mallID'];
            $mall_name = $mall_master['mallName'];

        }

        //核销条件为营业员或全部
        if ( $card_data['verify_type'] == 2 || $card_data['verify_type'] == 3 ) {

            if ( !isset( $sales_code ) ) {
                return response()->json(['code' => 10011, 'message' => '缺少参数：sales_code']);
            }

            //查询营业员信息是否存在
            $mall_user = MallUser::select('mallID','mallCode','mallName')->where(['employee_number'=>$sales_code ])->first();

            if ( !$mall_user ) {
                return response()->json(['code' => 10012, 'message' => '营业员信息不存在']);
            }

            $mall_id= $mall_user['mallID'];
            $mall_code = $mall_user['mallCode'];
            $mall_name = $mall_user['mallName'];

        }

        CardCouponCode::where(['barcode'=>$code])->update([
            'code_status'=>2,
            'sales_code'=>$sales_code,
            'mall_id'=>$mall_id,
            'mall_code'=>$mall_code,
            'mall_name'=>$mall_name,
            'used_time'=>Carbon::now()
        ]);

        return response()->json([ 'code' => 200 , 'message' => '核销成功']);

    }

    /**
     * 卡券转赠
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function give( Request $request )
    {

        $uid = $request->input('uid');
        $barcode = $request->input('code');
        $mobile = $request->input('mobile');
        $remark = $request->input('remark');
        $platform = $request->input('platform',6);
        $session_id = $request->input('session_id',session_id());

        if ( empty( $uid ) ) {
            return response()->json(['code' => 10001, 'message' => '缺少参数：uid']);
        }

        if ( empty( $barcode ) ) {
            return response()->json(['code' => 10002, 'message' => '缺少参数：code']);
        }

        if ( empty( $mobile ) ) {
            return response()->json(['code' => 10003, 'message' => '缺少参数：mobile']);
        }

        if ( !isMobile( $mobile ) ) {
            return response()->json(['code' => 10004, 'message' => '手机号码格式错误']);
        }

        $pcustID = get_customer_id($session_id,$platform);
        if ( $pcustID <=0 ) {
            return response()->json(['code' => 10005, 'message' => '请先登录']);
        }

        //查询会员信息
        $customer  = Customer::select('pcustID','custID','mobile')->where(['custID'=> $mobile])->first();
        if ( !$customer ) {
            $customer= Customer::select('pcustID','custID','mobile')->where(['mobile' => $mobile])->first();
            if ( !$customer ) {
                //获取会员等级
                $rank_data = CustRank::select('rankID','rankName')->where('useFlg',1)->orderBy('rankID', 'ASC')->first();
                if ( $rank_data ) {
                    $rankID = $rank_data['rankID'];
                    $rankName = $rank_data['rankName'];
                } else {
                    $rankID = 0;
                    $rankName = '';
                }

                $pwd = get_random_string(8, 'number');
                //注册会员
                $customer = new Customer();
                $customer->uuid = makeUuid();
                $customer->timeStamp = Carbon::now();
                $customer->creator = $mobile;
                $customer->createTime = Carbon::now();
                $customer->custID = $mobile;
                $customer->pcustID = generate_seqno('seqno_customer', '', true);
                $customer->useFlg = 1;
                $customer->custType = 1;
                $customer->rankID = $rankID;
                $customer->rankName = $rankName;
                $customer->pwd = md5($pwd);
                $customer->mobile = $mobile;
                $customer->save();
                //调用开卡接口
                WdhService::openCard([
                    'pcustID' => $customer->pcustID,
                    'custID' => $customer->custID,
                    'mobile' => $customer->mobile
                ]);
            }
        }

        if ( $pcustID == $customer->pcustID ) {
            return response()->json(['code' => 200, 'message' => '赠送成功']);
        }

        $card = CardCoupon::getFromUuid( $uid );

        if ( !$card ) {
            return response()->json(['code' => 10006, 'message' => '卡券不存在']);
        }

        if ( $card['can_give_friend'] == 0 ) {
            return response()->json(['code' => 10007, 'message' => '卡券不可以赠送']);
        } else if ($card['can_give_friend'] == 1) {
            $code_give =   CardCouponCodeGive::getCodeGive( $barcode );

            if ( $code_give) {
                return response()->json(['code' => 10008, 'message' => '该卡券只能转赠一次']);
            }
        }

        $give = CardCoupon::give( $card['card_id'],$barcode,$pcustID,$customer->pcustID,$remark );

        if ( $give['code'] != 200 ) {
            return response()->json(['code' => $give['code'], 'message' => $give['message']]);
        }

        //查询当前登录者的会员信息
        $current_customer = Customer::find($pcustID);

        //发送消息模板
        $push_params = [
            'pcustID' => $customer->pcustID,  //被赠送者的pcustID
            'keyword1' => $current_customer['mobile'], //赠送者的手机号
            'keyword2' => $remark
        ];

        $json_data = [
            'scene_id' => '1027',
            'params' => json_encode($push_params)
        ];

        WdhService::sendMessage( $json_data );

        return response()->json(['code' => 200, 'message' =>'赠送成功']);
    }

}